package com.sky.controller.user;

import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 菜品相关接口
 */
@RestController("userDishController")
@RequestMapping("/user/dish")
@Api(tags = "菜品相关接口（用户端）")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> searchDishesByCategory(@RequestParam Long categoryId) {
        log.info("根据分类id查询菜品，分类id：{}",categoryId);
        //查询redis中是否存在分类id对应的菜品数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object o = valueOperations.get("dish_" + categoryId);
        if(o!=null) { //如果存在，直接返回，无需访问数据库
            log.info("redis命中");
            return Result.success((List<DishVO>)o);//redis放进去是什么类型，取出来时候就要是什么类型
        } else { //如果不存在，查询数据库，将查询到的数据放入redis中
            log.info("redis未命中");
            List<DishVO> dishVOList = dishService.searchDishByCategory(categoryId);
            valueOperations.set("dish_"+categoryId,dishVOList);
            return Result.success(dishVOList);
        }
    }
}
